package cn.itcast.item.controller;
import cn.itcast.hmall.dto.common.PageDTO;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.item.SearchItemDTO;
import cn.itcast.item.pojo.Item;
import cn.itcast.item.service.ItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private ItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询商品
     * @param searchItemDTO item查询封装
     * @return
     */
    @PostMapping("/list")
    public PageDTO<Item> queryItemByPage(@RequestBody SearchItemDTO searchItemDTO) {

       return itemService.queryItemByPage(searchItemDTO);

    }

    /**
     * 根据id查询商品
     * @param id 商品id
     * @return
     */
    @GetMapping("/{id}")
    public Item queryItemById(@PathVariable("id") Long id){
        return itemService.queryItemById(id);
    }


    /**
     * 新增商品
     * @param item
     * @return
     */
    @PostMapping
    public ResultDTO saveItem(@RequestBody Item item){
        ResultDTO resultDTO = itemService.saveItem(item);
        //新增上架商品
        rabbitTemplate.convertAndSend("item.topic","item.up",item.getId());
        return resultDTO;
    }

    /**
     * 上架、下架商品
     * @param id
     * @param status
     * @return
     */
    @PutMapping("/status/{id}/{status}")
    public ResultDTO shelfItem(@PathVariable("id") Long id,
                                 @PathVariable("status") Integer status){
        ResultDTO resultDTO = itemService.shelfItem(id, status);
        //发送MQ消息
        if (status==1){
            //上架商品
            rabbitTemplate.convertAndSend("item.topic","item.up",id);
        }
        if (status==2){
            //下架商品
            rabbitTemplate.convertAndSend("item.topic","item.down",id);
        }
        return resultDTO;
    }

    /**
     * 修改商品
     * @param item
     * @return
     */
    @PutMapping
    public ResultDTO updateItem(@RequestBody Item item){
        return itemService.updateItem(item);
    }


    /**
     * 根据id删除商品
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public ResultDTO deleteItemById(@PathVariable("id") Long id){
        return itemService.deleteItemById(id);
    }







}
